<?php
namespace gnomephp\doctrine;
use Doctrine\ORM\EntityManager,
Doctrine\ORM\Configuration;
/**
 *
 * Doctrine specific class, use this to interact with Doctrine.
 * Uses database.yml in config folder.
 * @author peec
 *
 */
class Doctrine{

	/**
	 * Doctrine entity manager.
	 * Publically available.
	 * @var Doctrine\ORM\EntityManager
	 */
	static public $em = null;
	
	static private $loaded=false;
	static public function loadAutoloader(){
		require GNOME_FW_PATH . DIRECTORY_SEPARATOR . 'doctrine' . DIRECTORY_SEPARATOR . 'Doctrine'. DIRECTORY_SEPARATOR .'Common'. DIRECTORY_SEPARATOR .'ClassLoader.php';

		$classLoader = new \Doctrine\Common\ClassLoader('Doctrine', (GNOME_FW_PATH . DIRECTORY_SEPARATOR . 'doctrine') );
		$classLoader->register(); // register on SPL autoload stack

		$classloader = new \Doctrine\Common\ClassLoader('Symfony', (GNOME_FW_PATH . DIRECTORY_SEPARATOR . 'doctrine' . DIRECTORY_SEPARATOR . 'Doctrine') );
		$classloader->register();		
	}
	
	static public function load(){
		if (!self::$loaded){
		self::loadAutoloader();


		if (\gnomephp\Configuration::get('application', 'debug_mode') == true){
			$gnomeConfigSet = \gnomephp\Configuration::get('database', 'development');
		}else{
			$gnomeConfigSet = \gnomephp\Configuration::get('database', 'production');
		}
		
		$caceDriverClass = '\Doctrine\Common\Cache\\'.$gnomeConfigSet['cache_driver'];
		
		if (\gnomephp\Configuration::get('application', 'debug_mode') == true) {
			// $cache = new $caceDriverClass;
		} else {
			// $cache = new $caceDriverClass;
		}

		$config = new Configuration;
		// $config->setMetadataCacheImpl($cache);
		$driverImpl = $config->newDefaultAnnotationDriver(GNOME_APP_PATH . DIRECTORY_SEPARATOR . 'model');
		$config->setMetadataDriverImpl($driverImpl);
		// $config->setQueryCacheImpl($cache);
		$config->setProxyDir(GNOME_APP_PATH . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . 'doctrine' . DIRECTORY_SEPARATOR . 'Proxies');
		$config->setProxyNamespace(GNOME_APP_NS . '\Doctrine\Proxies');

		if (\gnomephp\Configuration::get('application', 'debug_mode') == true) {
			$config->setAutoGenerateProxyClasses(true);
		} else {
			$config->setAutoGenerateProxyClasses(false);
		}

		
		
		self::$em = EntityManager::create($gnomeConfigSet, $config);
		self::$loaded = true;
		}
	}
	
	/**
	 * @return Doctrine\ORM\EntityManager The entity manager of Doctrine.
	 */
	static public function getEM(){
		return self::$em;
	}


}